package com.sunwayhorizo.health.hl7.rim;

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;
import javax.persistence.*;
import com.sunwayhorizo.health.hl7.common.*;
import com.sunwayhorizo.health.hl7.datatypes.*;
import com.sunwayhorizo.health.hl7.datatypes.common.*;
import com.sunwayhorizo.health.hl7.factories.*;
import com.sunwayhorizo.health.hl7.persistent.*;
import com.sunwayhorizo.health.hl7.vocabulary.RoleIICode;
import com.sunwayhorizo.health.hl7.vocabulary.RoleCdSetCode;

import static com.sunwayhorizo.health.hl7.vocabulary.RoleCdSetCode.*;

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorValue("ROL")
public class Role extends RimCoreRoles implements Serializable
{
    private static final long serialVersionUID = 1L;
    /*
     * public BAG_AD addr; public ED CertificateText; public SET_CE
     * confidentialityCode; public CS ClassCode; public CE code; public GTS
     * effectiveTime; public SET_II id; public BL negationInd; public Iterator
     * participations; public Hl7Entity playerEntity; public LIST_INT
     * positionNumber; public RTO_PQ quantity; public Hl7Entity scoperEntity;
     * public CS statusCode; public BAG_TEL telecom;
     */

    @Column(name = "ROLE_NAME")
    private String roleName; // 先简单处理,robo加，角色名称

    @Column(name = "OWNER_CODE")
    private String ownerCode; // 自身拥有

    @Column(name = "PRIORITY_NUMBER")
    private String priorityNumber;


    public Role()
    {
    }


    public CE getVisitType()
    {
        return DataTypeUtil.getCE(getRimCoreRoleCdSets(VISITTYPECODE));
    }


    public void setVisitType(CE visitType)
    {
        setRimCoreRoleCdSets(visitType, VISITTYPECODE);
    }


    public Role(ReferenceModifier referencemodifier)
    {

        super(referencemodifier);
    }


    // 新增地址
    private void newAddr(AD addr)
    {
        RimCoreRoleAddrs roleAddrs = new RimCoreRoleAddrs();
        roleAddrs.setLiteral(addr.formatted().toString());
        roleAddrs.setRoleAddrUses(addr.use().toSet());
        roleAddrs.setRoleAddrParts(addr.toList());
        this.addRoleAddrs(roleAddrs);
    }


    /**
     * 设置Role的地址信息 所有继承与Role的角色实体保存修改都用次方法
     * 
     * @param addr
     *            地址信息
     */
    @SuppressWarnings("rawtypes")
    public void setAddr(AD addr)
    {
        List mList = addr.toList();
        List<RimCoreRoleAddrs> addrList = this.getRoleAddrsList();
        if (ListUtil.isNotEmpty(addrList))
        {
            for (int i = 0; i < addrList.size(); i++)
            {
                RimCoreRoleAddrs addrs = addrList.get(i);
                String addrFormat = "";
                List<RimCoreRoleAddrParts> addrParts = addrs.getRimCoreRoleAddrPartsList();
                if (ListUtil.isNotEmpty(addrParts))
                {
                    for (int j = 0; j < addrParts.size(); j++)
                    {
                        RimCoreRoleAddrParts addPart = addrParts.get(j);
                        for (int k = 0; k < mList.size(); k++)
                        {
                            ADXPImpl ad = (ADXPImpl) mList.get(k);
                            if (addPart.getPartType().equals(ad.partType().code().toString()))
                            {
                                addrFormat += ad.literal().toString();
                                addPart.setLiteral(ad.literal().toString());
                                addPart.setPartOrderNum((long) k);
                            }
                        }
                    }
                }
                addrs.setLiteral(addrFormat);
            }
        }
        else
        {
            newAddr(addr);
        }
    }


    /**
     * 得到Role的地址信息
     * 
     * @return BAG_AD
     * @throws Hl7Exception
     */
    @SuppressWarnings("rawtypes")
    public BAG_AD getAddr() throws Hl7Exception
    {
        RimCoreRoleAddrs roleAddrs = (RimCoreRoleAddrs) this.getRoleAddrsList().get(0);
        List mList = roleAddrs.getRimCoreRoleAddrPartsList();
        int size = mList.size();
        String value[] = new String[size];
        String type[] = new String[size];
        for (int i = 0; i < size; i++)
        {
            RimCoreRoleAddrParts partAddr = (RimCoreRoleAddrParts) mList.get(i);
            value[i] = partAddr.getLiteral();
            type[i] = partAddr.getPartType();
        }

        String useCode = new String();
        RimCoreRoleAddrUses addrUses = (RimCoreRoleAddrUses) roleAddrs.getRimCoreRoleAddrUsesList().get(0);
        useCode = addrUses.getUse();

        return DataTypeUtil.getBagAD(DataTypeUtil.getAD(value, type, useCode));
    }


    public void setCertificateText(ED CertificateText)
    {
        RimCoreEds ed = this.getRimCoreEdsCertificateTxtEdId();
        converRimCoreEds(ed, CertificateText);
        this.setRimCoreEdsCertificateTxtEdId(ed);
    }


    public ED getCertificateText() throws Hl7Exception
    {
        RimCoreEds ed = this.getRimCoreEdsCertificateTxtEdId();
        return DataTypeUtil.getED(new String(ed.getEdClob()));
    }


    public void setConfidentialityCode(CE ce)
    {

        if (null != ce && ce.codeSystemEnName() != null && ce.codeName() != null)
        {
            setRimCoreRoleCdSets(ce, CONFIDENTIALITYCODE);
        }
        else
        {
            this.setConfidentialityCodeEtsId(ce.code().toString());
        }
    }


    public CE getConfidentialityCode() throws Hl7Exception
    {
        if (this.getConfidentialityCodeEtsId().equals(CONFIDENTIALITYCODE.toString()))
        {
            for (RimCoreRoleCdSets roleCdSets : this.getRoleCdSetsList())
            {
                if (this.getConfidentialityCodeEtsId().equals(roleCdSets.getAttributeTypeCode()))
                {
                    return (DataTypeUtil.getCE(roleCdSets));
                }
            }
        }
        else
            return (DataTypeUtil.getCE(this.getConfidentialityCodeEtsId()));
        return null;
    }


    public void setTypeCodeEts(CE typeCodeEts)
    {
        if (null != typeCodeEts && typeCodeEts.codeSystemEnName() != null && typeCodeEts.codeName() != null)
        {
            setRimCoreRoleCdSets(typeCodeEts, TYPECODE);
        }
        else
        {
            this.setTypeCodeEtsId(typeCodeEts.code().toString());
        }
    }


    /**
     * 得到Role的类型字典（该方法可以存放Role的一些公共属性进去，比如科室类型，床位类型的）
     * 
     * @return CE
     * @throws Hl7Exception
     */
    public CE getTypeCodeEts() throws Hl7Exception
    {
        if (null != this.getTypeCodeEtsId() && this.getTypeCodeEtsId().equals(TYPECODE.toString()))
        {
            for (RimCoreRoleCdSets roleCdSets : this.getRoleCdSetsList())
            {
                if (this.getTypeCodeEtsId().equals(roleCdSets.getAttributeTypeCode()))
                {
                    return DataTypeUtil.getCE(roleCdSets);
                }
            }
        }
        else
            return DataTypeUtil.getCE(this.getTypeCodeEtsId());
        return null;
    }


    public void setEffectiveTime(GTS effectiveTime)
    {
        this.setEffectiveStartDateTs(new Timestamp(effectiveTime.hull().low().toDate().getTime()));
        this.setEffectiveEndDateTs(new Timestamp(effectiveTime.hull().high().toDate().getTime()));
        this.setEffectiveDateGtsTxt(effectiveTime.literal().toString());
    }


    public GTS getEffectiveTime()
    {
        return null;
    }


    public void setNegationInd(BL negationInd)
    {
        this.setNegationFlag(negationInd.toString());
    }


    public BL getNegationInd() throws Hl7Exception
    {
        return DataTypeUtil.getBL(this.getNegationFlag());
    }


    public void setPlayerEntity(Hl7Entity playerEntity)
    {
        this.setPlayerEntities(playerEntity);
    }


    public Hl7Entity getPlayerEntity()
    {
        return (Hl7Entity) this.getPlayerEntities();
    }


    public void setScoperEntity(Hl7Entity scoperEntity)
    {
        this.setScoperEntities(scoperEntity);
    }


    public Hl7Entity getScoperEntity()
    {
        return (Hl7Entity) this.getScoperEntities();
    }


    /*
     * public void setPositionNumber(LIST_INT positionNumber) { this =
     * positionNumber; }
     * 
     * public LIST_INT getPositionNumber() { return null; }
     */
    public void setQuantity(RTO_PQ quantity)
    {
        this.setQtyNumerTxt(quantity.numerator().value().toString());
        this.setQtyNumerUomCode(quantity.numerator().unit().code().toString());
        this.setQtyDenomTxt(quantity.denominator().value().toString());
        this.setQtyDenomUomCode(quantity.denominator().unit().toString());
    }


    public RTO_PQ getQuantity() throws Hl7Exception
    {
        return DataTypeUtil.getRTO_PQ(this.getQtyNumerTxt(), this.getQtyNumerUomCode(), this.getQtyDenomTxt(), this.getQtyDenomUomCode());
    }


    /**
     * 获得指定identifierName类型的id
     * 
     * @param identifierName
     *            唯一标识符
     * @return II
     * @throws Hl7Exception
     */
    public II getId(RoleIICode identifierName) throws Hl7Exception
    {
        if (identifierName == null)
        {
            return null;
        }
        for (RimCoreRoleIi ii : getRoleIiList())
        {
            if (identifierName.toString().equals(ii.getIdentifierName()))
            {
                return DataTypeUtil.getII(ii.getExtensionTxt(), ii.getIDSouce(), ii.getDisplayableFlag(), DataTypeUtil.getCE(ii.getRimCoreRoleCdSets()),
                    ii.getIdentifierName());
            }
        }
        return null;
    }


    /**
     * 设置角色id
     * 
     * @param id
     *            角色id唯一性值
     */
    public void setId(II id)
    {
        String identifierName = id.identifierName().stringValue();
        if (StrUtil.isEmpty(identifierName))
        {
            return;
        }
        setId(id, RoleIICode.valueOf(identifierName));
    }


    // 保存电话list信息
    @SuppressWarnings({ "rawtypes" })
    private void newTelecomList(BAG_TEL telecom)
    {
        List mList = telecom.toList();
        for (int i = 0; i < mList.size(); i++)
        {
            TELImpl tel = (TELImpl) mList.get(i);
            newTelecom(tel);
        }
    }


    // 保存一个电话信息
    private void newTelecom(TELImpl tel)
    {
        RimCoreRoleTelAddrs roleTelAddrs = new RimCoreRoleTelAddrs();
        roleTelAddrs.setAddress(tel.address().toString());
        roleTelAddrs.setScheme(tel.scheme().toString());
        roleTelAddrs.setEffectiveStartDateTs(new Timestamp(tel.useablePeriod().hull().low().toDate().getTime()));
        roleTelAddrs.setEffectiveEndDateTs(new Timestamp(tel.useablePeriod().hull().high().toDate().getTime()));
        roleTelAddrs.setEffectiveGtsTxt(tel.useablePeriod().literal().toString());
        roleTelAddrs.setRoleTelAddrUses(tel.use().toSet());
        this.addRoleTelAddrs(roleTelAddrs);
    }


    /**
     * 设置电话属性 所有继承与Role 的实体添加，修改都用此方法
     * 
     * @param telecom
     *            电话信息
     */
    @SuppressWarnings("rawtypes")
    public void setTelecom(BAG_TEL telecom)
    {
        List mList = telecom.toList();
        for (int j = 0; j < mList.size(); j++)
        {
            TELImpl tel = (TELImpl) mList.get(j);
            CSImpl useCode = (CSImpl) tel.use().toSet().iterator().next();
            String newUse = useCode.code().toString();
            List<RimCoreRoleTelAddrs> listTelAddrs = this.getRoleTelAddrsList();
            if (ListUtil.isNotEmpty(listTelAddrs))
            {
                if (listTelAddrs.size() > j)
                {
                    RimCoreRoleTelAddrs telAddr = (RimCoreRoleTelAddrs) listTelAddrs.get(j);
                    String oldUse = telAddr.getRimCoreRoleTelUsesList().get(0).getUseCode();
                    if (oldUse.equals(newUse))
                    {
                        telAddr.setAddress(tel.address().toString());
                        telAddr.setScheme(tel.scheme().toString());
                        telAddr.setEffectiveStartDateTs(new Timestamp(tel.useablePeriod().hull().low().toDate().getTime()));
                        telAddr.setEffectiveEndDateTs(new Timestamp(tel.useablePeriod().hull().high().toDate().getTime()));
                        telAddr.setEffectiveGtsTxt(tel.useablePeriod().literal().toString());
                    }
                }
                if (listTelAddrs.size() <= j)
                {
                    newTelecom(tel);
                }
            }
            else
            {
                newTelecomList(telecom);
            }
        }
    }


    /**
     * 得到电话集合
     * 
     * @return BAG_TEL
     * @throws Hl7Exception
     * @SuppressWarnings("rawtypes")
     */
    @SuppressWarnings("rawtypes")
    public BAG_TEL getTelecom() throws Hl7Exception
    {
        List mList = this.getRoleTelAddrsList();
        int size = mList.size();
        String scheme[] = new String[size];
        String address[] = new String[size];
        String telUseCode[] = new String[size];
        Date useablePeriod[][] = new Date[size][2];

        for (int i = 0; i < size; i++)
        {
            RimCoreRoleTelAddrs roleTelAddrs = (RimCoreRoleTelAddrs) mList.get(i);
            scheme[i] = roleTelAddrs.getScheme();
            address[i] = roleTelAddrs.getAddress();
            useablePeriod[i][0] = roleTelAddrs.getEffectiveStartDateTs();
            useablePeriod[i][1] = roleTelAddrs.getEffectiveEndDateTs();

            List mmList = roleTelAddrs.getRimCoreRoleTelUsesList();
            RimCoreRoleTelUses roleTelUses = (RimCoreRoleTelUses) mmList.get(0);
            telUseCode[i] = roleTelUses.getUseCode();
        }

        return DataTypeUtil.getBAG_TEL(scheme, address, useablePeriod, telUseCode);
    }


    @SuppressWarnings("unchecked")
    public List<Rolelink> getSourceRolelinks()
    {

        return (List<Rolelink>) getSourceRoleRimCoreRoleLink();

    }


    @SuppressWarnings("unchecked")
    public List<Rolelink> getTargetRolelinks()
    {

        return (List<Rolelink>) getTargetRoleRimCoreRoleLink();

    }


    /**
     * 通过Role得到ActParticipation
     */
    @SuppressWarnings("unchecked")
    public List<ActParticipation> getParticipations()
    {
        return (List<ActParticipation>) this.getRolePrtcptnsList();
    }


    /**
     * 在participation 中加入role
     * 
     * @param actPrtcptns
     * @return
     */
    @SuppressWarnings("unchecked")
    public ActParticipation addRolePrtcptns(ActParticipation actPrtcptns)
    {
        ((List<ActParticipation>) getRolePrtcptnsList()).add(actPrtcptns);
        actPrtcptns.setRoleparticipation(this);
        return actPrtcptns;
    }


    /**
     * 从participation删除role（只删除participation与role的关系）
     * 
     * @param actPrtcptns
     * @return
     */
    public ActParticipation removeRolePrtcptns(ActParticipation actPrtcptns)
    {
        getRolePrtcptnsList().remove(actPrtcptns);
        actPrtcptns.setRoleparticipation(null);
        return actPrtcptns;
    }


    /**
     * 
     * @Title: addSourceRoleLink
     * @param @param arType
     * @param @param source 设定文件
     * @return void 返回类型
     * @throws
     * @firstAuthor jinzw
     * @firstTime 2010-11-16 下午07:24:46
     * @lastAuthor jinzw
     * @lastTime 2010-11-16 下午07:24:46
     */
    public void addSourceRoleLink(CS typeCode, Role sourceRole)
    {
        Rolelink rimCoreRoleLink = new Rolelink();
        rimCoreRoleLink.setTypeCode(typeCode);

        rimCoreRoleLink.setSourceRole(sourceRole);
        rimCoreRoleLink.setTargetRole(this);

        ControlAct controlAct = (ControlAct) sourceRole.getControlAct();
        controlAct.addControlActRole(this); // controlAct维护role
        controlAct.addControlActRoleLink(rimCoreRoleLink); // controlAct维护roleLink
    }


    /**
     * 添加rolelink关系
     * 
     * @param typeCode
     *            两个role之间的关系
     * @param target
     *            目标role
     * @param relationType
     *            家庭关系 从字典取
     * @param describe
     *            描述
     * @param priorityNumber
     *            排序
     * @throws Hl7Exception
     */
    public void addTargetRoleLink(CS typeCode, Role target, CS relationType, CS describe, INT priorityNumber) throws Hl7Exception
    {

        Rolelink rimCoreRoleLink = new Rolelink();
        rimCoreRoleLink.setTypeCode(typeCode);
        rimCoreRoleLink.setRelation(relationType);
        rimCoreRoleLink.setDescribe(describe);
        rimCoreRoleLink.setSequenceNumber(priorityNumber);

        rimCoreRoleLink.setSourceRole(this);
        rimCoreRoleLink.setTargetRole(target);

        ControlAct controlAct = (ControlAct) target.getControlAct();
        if (controlAct == null)
            return;
        controlAct.addControlActRole(target); // controlAct维护role
        controlAct.addControlActRoleLink(rimCoreRoleLink); // controlAct维护roleLink
    }

    // Role

    @Column(name = "NEGATION_FLAG")
    private String negationFlag;
    @Column(name = "TYPE_CODE_ETS_ID")
    private String typeCodeEtsId = TYPECODE.toString();
    // effectiveTime
    @Column(name = "EFFECTIVE_DATE_GTS_TXT")
    private String effectiveDateGtsTxt;
    @Column(name = "EFFECTIVE_END_DATE_TS")
    private Timestamp effectiveEndDateTs;
    @Column(name = "EFFECTIVE_START_DATE_TS")
    private Timestamp effectiveStartDateTs;

    // @Column(name = "CERTIFICATE_TXT_ED_ID") private Long certificateTxtEdId;
    @Column(name = "CONFIDENTIALITY_CODE_ETS_ID")
    private String confidentialityCodeEtsId = CONFIDENTIALITYCODE.toString();

    // quantity
    @Column(name = "QTY_DENOM_TXT")
    private String qtyDenomTxt;
    @Column(name = "QTY_DENOM_UOM_CODE")
    private String qtyDenomUomCode;
    @Column(name = "QTY_NUMER_TXT")
    private String qtyNumerTxt;
    @Column(name = "QTY_NUMER_UOM_CODE")
    private String qtyNumerUomCode;


    /*
     * private Long getCertificateTxtEdId() { return certificateTxtEdId; }
     * 
     * private void setCertificateTxtEdId(Long certificateTxtEdId) {
     * this.certificateTxtEdId = certificateTxtEdId; }
     */

    protected String getConfidentialityCodeEtsId()
    {
        return confidentialityCodeEtsId;
    }


    protected void setConfidentialityCodeEtsId(String confidentialityCodeEtsId)
    {
        this.confidentialityCodeEtsId = confidentialityCodeEtsId;
    }


    protected String getNegationFlag()
    {
        return negationFlag;
    }


    protected void setNegationFlag(String negationFlag)
    {
        this.negationFlag = negationFlag;
    }


    public String getEffectiveDateGtsTxt()
    {
        return effectiveDateGtsTxt;
    }


    public void setEffectiveDateGtsTxt(String effectiveDateGtsTxt)
    {
        this.effectiveDateGtsTxt = effectiveDateGtsTxt;
    }


    @SuppressWarnings("unused")
    protected Timestamp getEffectiveEndDateTs()
    {
        return effectiveEndDateTs;
    }


    public void setEffectiveEndDateTs(Timestamp effectiveEndDateTs)
    {
        this.effectiveEndDateTs = effectiveEndDateTs;
    }


    @SuppressWarnings("unused")
    protected Timestamp getEffectiveStartDateTs()
    {
        return effectiveStartDateTs;
    }


    public void setEffectiveStartDateTs(Timestamp effectiveStartDateTs)
    {
        this.effectiveStartDateTs = effectiveStartDateTs;
    }


    public String getQtyDenomTxt()
    {
        return qtyDenomTxt;
    }


    private void setQtyDenomTxt(String qtyDenomTxt)
    {
        this.qtyDenomTxt = qtyDenomTxt;
    }


    protected String getQtyDenomUomCode()
    {
        return qtyDenomUomCode;
    }


    private void setQtyDenomUomCode(String qtyDenomUomCode)
    {
        this.qtyDenomUomCode = qtyDenomUomCode;
    }


    public String getQtyNumerTxt()
    {
        return qtyNumerTxt;
    }


    private void setQtyNumerTxt(String qtyNumerTxt)
    {
        this.qtyNumerTxt = qtyNumerTxt;
    }


    protected String getQtyNumerUomCode()
    {
        return qtyNumerUomCode;
    }


    private void setQtyNumerUomCode(String qtyNumerUomCode)
    {
        this.qtyNumerUomCode = qtyNumerUomCode;
    }


    public String getRoleName()
    {
        return roleName;
    }


    public void setRoleName(String roleName)
    {
        this.roleName = roleName;
    }


    public String getOwnerCode()
    {
        return ownerCode;
    }


    public void setOwnerCode(String ownerCode)
    {
        this.ownerCode = ownerCode;
    }


    public String getPriorityNumber()
    {
        return priorityNumber;
    }


    public void setPriorityNumber(String priorityNumber)
    {
        this.priorityNumber = priorityNumber;
    }


    public void addTargetRole(Rolelink targetRolelink)
    {
        getTargetRolelinks().add(targetRolelink);

    }


    public void addSourceRole(Rolelink sourceRolelink)
    {
        getSourceRolelinks().add(sourceRolelink);

    }


    protected String getTypeCodeEtsId()
    {
        return typeCodeEtsId;
    }


    private void setTypeCodeEtsId(String typeCodeEtsId)
    {
        this.typeCodeEtsId = typeCodeEtsId;
    }


    // 将CE的属性值赋给RimCoreRoleCdSets
    protected RimCoreRoleCdSets convertRimCoreRoleCdSets(RimCoreRoleCdSets cdsets, CE ce)
    {
        if (ce != null)
        {
            cdsets.setCodingschemeChName(ce.codeSystemChName().isNull().booleanValue() ? null : ce.codeSystemChName().stringValue());
            cdsets.setCodingschemeEnName(ce.codeSystemEnName().isNull().booleanValue() ? null : ce.codeSystemEnName().stringValue());
            cdsets.setConceptName(ce.codeName().isNull().booleanValue() ? null : ce.codeName().stringValue());
            cdsets.setCodingschemeVersionName(ce.codeSystemVersion().isNull().booleanValue() ? null : ce.codeSystemVersion().stringValue());
            cdsets.setConceptCode(ce.code().isNull().booleanValue() ? null : ce.code().stringValue());
            cdsets.setCodingschemeOid(ce.codeSystem().isNull().booleanValue() ? null : ce.codeSystem().stringValue());
        }
        return cdsets;
    }


    // 将II的属性值赋给RimCoreRoleIi
    protected RimCoreRoleIi convertRimCoreRoleIi(RimCoreRoleIi roleii, II ii)
    {
        roleii.setRootId(ii.root().stringValue());
        roleii.setExtensionTxt(ii.extension().stringValue());
        roleii.setDisplayableFlag(ii.iiState() != null ? ii.iiState().stringValue() : null);
        roleii.setIDSouce((ii.iiSouce() == null || ii.iiSouce().isNull().booleanValue()) ? null : ii.iiSouce().stringValue());
        roleii.setLastUpdateDate(new Timestamp(new Date().getTime()));
        roleii.setLastUpdatedBy(getLastUpdatedBy());
        return roleii;
    }


    /**
     * 
     * @Title: setRimCoreRoleCdSets
     * @Description: 根据
     * @param dicCode
     *            ce字典类型
     * @param attributeTypeCode
     *            匹配属性名称
     * @firstAuthor Obama
     * @firstTime 2011-07-01 13:14:58
     * @lastAuthor Obama
     * @lastTime 2011-07-301 13:14:58
     */
    protected void setRimCoreRoleCdSets(CE dicCode, RoleCdSetCode attributeTypeCode)
    {
        for (RimCoreRoleCdSets cdsets : getRoleCdSetsList())
        {
            if (cdsets.getAttributeTypeCode() != null && cdsets.getAttributeTypeCode().equals(attributeTypeCode.toString()))
            {
                // attributeTypeCode匹配直接更新
                convertRimCoreRoleCdSets(cdsets, dicCode);
                return;
            }
        }
        // 没有匹配新建
        RimCoreRoleCdSets rcrc = new RimCoreRoleCdSets();
        rcrc.setAttributeTypeCode(attributeTypeCode.toString());
        addRoleCdSets(convertRimCoreRoleCdSets(rcrc, dicCode));
    }


    protected RimCoreRoleCdSets getRimCoreRoleCdSets(RoleCdSetCode attributeTypeCode)
    {
        if (attributeTypeCode == null)
        {
            return null;
        }
        for (RimCoreRoleCdSets cdsets : getRoleCdSetsList())
        {
            if (cdsets.getAttributeTypeCode() != null && cdsets.getAttributeTypeCode().equals(attributeTypeCode.toString()))
            {
                return cdsets;
            }
        }
        return null;
    }


    // 设置指定identifierName类型的id
    protected void setId(II id, RoleIICode identifierName)
    {
        if (identifierName == null)
        {
            return;
        }
        for (RimCoreRoleIi ii : getRoleIiList())
        {
            if (ii.getIdentifierName().equals(identifierName.toString()))
            {
                // 匹配identifierName更新roleii
                convertRimCoreRoleIi(ii, id);
                ii.setRimCoreRoleCdSets(convertRimCoreRoleCdSets(ii.getRimCoreRoleCdSets(), id.iiType()));

                return;
            }
        }
        // 都不匹配identifierName新建roleii
        RimCoreRoleIi roleii = new RimCoreRoleIi();

        if (id.iiType() != null && !id.iiType().isNull().booleanValue())
        {
            RimCoreRoleCdSets roleCdSets = new RimCoreRoleCdSets();
            roleii.setRimCoreRoleCdSets(convertRimCoreRoleCdSets(roleCdSets, id.iiType()));
            addRoleCdSets(roleCdSets);
        }
        roleii.setIdentifierName(identifierName.toString());
        roleii.setCreatedBy(getCreatedBy());
        roleii.setCreationDate(new Timestamp(new Date().getTime()));

        addRoleIi(convertRimCoreRoleIi(roleii, id));
    }


    protected void converRimCoreEds(RimCoreEds rimCoreEd, ED ed)
    {
        if (rimCoreEd == null)
        {
            rimCoreEd = new RimCoreEds();
        }
        rimCoreEd.setEdBlob(ed.integrityCheck().byteArray()); // 二进制文件
        rimCoreEd.setEdClob(ed.literal().toString().toCharArray()); // 大文本
        rimCoreEd.setMediaTypeCode(ed.mediaType().toString());
        rimCoreEd.setCharacterSetCode(ed.charset().toString());
        rimCoreEd.setLanguageCode(ed.language().toString());
        rimCoreEd.setCompressionCode(ed.compression().toString());
        rimCoreEd.setRefTelAddressTxt(ed.reference().address().toString());
        rimCoreEd.setRefTelSchemeCode(ed.reference().scheme().toString());
        if (null != ed.reference().useablePeriod().hull().low())
        {
            rimCoreEd.setRefTelStartDateTs(new Timestamp(ed.reference().useablePeriod().hull().low().toDate().getTime()));
        }
        if (null != ed.reference().useablePeriod().hull().high())
        {
            rimCoreEd.setRefTelEndDateTs(new Timestamp(ed.reference().useablePeriod().hull().high().toDate().getTime()));
        }
        rimCoreEd.setRefTelGtsTxt(ed.reference().useablePeriod().literal().toString());
        rimCoreEd.setEdRefTelUses(ed.reference().use().toSet());
        rimCoreEd.setIntegrityCheckAlgCode(ed.integrityCheckAlgorithm().toString());
        /*
         * if (!ed.integrityCheck().isNull().booleanValue()) { //次属性测试有问题，暂时屏蔽
         * rimCoreEd.setIntegrityCheckTxt(ed.integrityCheck().stringValue()); }
         */
    }

}
